<script setup lang="ts">
import { getCouponPackListApi } from '@/services/eat'
import { useDeviceStore, useLocationStore, useMemberStore, usePagesMachineIdStore } from '@/stores'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { inject, nextTick, ref } from 'vue'
const { loginPromise } = <{ loginPromise: Promise<unknown> }>inject('globalData')
const { SkipPopupRef, receive, skipPopupData, handleClose } = usePopup()

const memberStore = useMemberStore() // 获取本地缓存
const deviceStore = useDeviceStore()
const locationStore = useLocationStore()
// 获取礼包商品列表
const couponPackList = ref<any[]>([])
const getCouponPackList = async () => {
  try {
    const res = await getCouponPackListApi()
    couponPackList.value = res?.data || []
    if (rulePopupObj.value?.isShare) {
      nextTick(() => {
        rulePopupObj.value =
          couponPackList.value.find((item) => item.id === rulePopupObj.value.id) || {}
        if (rulePopupObj.value.id) {
          rulePopupRef?.value.popupOpen()
        }
      })
    }
  } catch (error) {
    console.log(error)
  }
}

/**
 * 登录弹出层实例
 */
const popupRef = ref()

/** 触发规则组件 */
const rulePopupObj = ref<any>({})
const rulePopupRef = ref()
const triggerRules = (obj: any) => {
  rulePopupObj.value = obj
  rulePopupRef?.value.popupOpen()
  const shareParams = {
    path: `/pagesMy/couponPack/couponPack?machineId=${'24083004000028'}&machineName=${
      deviceStore?.deviceInfo?.machineName
    }&positionAddr=${deviceStore?.deviceInfo?.positionAddr}&businessStatus=${
      deviceStore?.deviceInfo?.businessStatus
    }&saleBeginTime=${deviceStore?.deviceInfo?.saleBeginTime}&saleEndTime=${
      deviceStore?.deviceInfo?.saleEndTime
    }&id=${obj.id}&share=true`,
    title: obj.name,
  }
  setupOnShareAppMessage(shareParams)
}
/**
 * 跳转到结算页面
 */
const goToPay = (obj?: any) => {
  if (!obj.currentStock || !obj.canBuy) return
  if (memberStore.userInfo && obj) {
    uni.navigateTo({
      url:
        '/pagesEat/billingPage/billingPage?type=couponPack&back=true&couponPackInfo=' +
        JSON.stringify(obj),
    }) // 进行跳转
    rulePopupObj.value = false
    return
  } else {
    popupRef.value.open()
  }
}

onShow(() => {
  loginPromise.then(() => {
    getCouponPackList()
  })
})

const handleShow = ref(true)
const pagesMachineId = usePagesMachineIdStore()

/** 获取设备列表信息 */
const getspotList = async () => {
  try {
    const res = await getMachineDataApi({
      machineId: pagesMachineId.pagesMachineId || null,
      clientId: memberStore.userInfo?.id || '',
      longitude: locationStore.location!.longitude,
      latitude: locationStore.location!.latitude,
      pageNum: 1,
      pageSize: 3,
    })
    let machineItem = res.data?.find((i: any) => pagesMachineId.pagesMachineId === i.machineId)
    machineItem ? deviceStore.setDeviceInfo(machineItem) : null
  } catch (error) {
    console.log('catch', error)
  }
}
/**
 * * 获取当前地点最近的设备并且赋值
 * @param machineName 设备名称
 */
const { deviceId } = uni.getSystemInfoSync() // 获取登录设备信息
const getMachineList = async () => {
  let itemDevice
  try {
    const res = await getMachineDataApi({
      machineId: pagesMachineId.pagesMachineId || null,
      clientId: memberStore.userInfo?.id || '',
      longitude: locationStore.location!.longitude,
      latitude: locationStore.location!.latitude,
      pageNum: 1,
      pageSize: 50,
    })

    itemDevice = res.data?.find((item: any) => {
      if (item.machineId === pagesMachineId.pagesMachineId) return item
    })
    console.log('itemDevice', itemDevice)
    if (!itemDevice || Object.keys(itemDevice).length === 0) {
      itemDevice = res.data?.find((item: any) => {
        if (item.businessStatus === '运营中') return item
      })
    }
    deviceStore.setDeviceInfo(itemDevice)
  } catch (error) {
    console.log(error)
  }
  postActivityDegreeApi({
    machineId: itemDevice?.machineId,
    temporarySign: memberStore.token ? null : deviceId,
  })
}
onLoad((ev) => {
  console.log('ev', ev)
  ev?.machineId ? pagesMachineId.setPagesMachineId(ev.machineId) : null
  if (ev?.q) {
    console.log(
      'extractQueryParams(decodeURIComponent(decodeURIComponent(ev?.q)))',
      extractQueryParams(decodeURIComponent(decodeURIComponent(ev?.q))),
    )
    // ev?.machineId ? pagesMachineId.setPagesMachineId(extractQueryParams(ev).machineId) : null
  }
  console.log('deviceStore', deviceStore)
  if (deviceStore?.deviceInfo?.machineName) {
    loginPromise.then(() => {
      getspotList()
    })
  } else {
    loginPromise.then(() => {
      getMachineList()
    })
  }
  if (ev?.id) {
    rulePopupObj.value.isShare = true
    rulePopupObj.value.id = Number(ev?.id)
  }
  if (ev?.share) {
    if (ev?.machineId) {
      handleShow.value = true
    } else {
      handleShow.value = false
    }
  } else {
    handleShow.value = true
  }
  const shareParams = {
    path: `/pagesMy/couponPack/couponPack?machineId=${deviceStore?.deviceInfo?.machineId}&machineName=${deviceStore?.deviceInfo?.machineName}&positionAddr=${deviceStore?.deviceInfo?.positionAddr}&businessStatus=${deviceStore?.deviceInfo?.businessStatus}&saleBeginTime=${deviceStore?.deviceInfo?.saleBeginTime}&saleEndTime=${deviceStore?.deviceInfo?.saleEndTime}&share=true`,
    title: deviceStore?.deviceInfo?.machineName,
  }
  setupOnShareAppMessage(shareParams)
})

// 调用小程序的分享，以及监听小程序分享
import useMiniShare from '@/hooks/useMiniShare'
import { getMachineDataApi } from '@/services/home'
import usePopup from '@/hooks/usePopup'
import { extractQueryParams } from '@/utils/tools'
import { postActivityDegreeApi } from '@/services/component'
const { isShareFriends, onShareAppMessage, setupOnShareAppMessage } = useMiniShare()
isShareFriends()
onShareAppMessage
</script>
<template>
  <view>
    <!-- 套餐组件 -->
    <scroll-view scroll-y :show-scrollbar="false" class="rightGoods_scroll">
      <!-- 每个类别盒子 -->
      <view class="itemBox" v-if="couponPackList?.length > 0 && handleShow">
        <view
          v-for="item in couponPackList"
          :key="item.id"
          class="item"
          :class="item.currentStock <= 0 || !item.canBuy ? 'stocksIF' : ''"
          @click.stop="triggerRules(item)"
        >
          <!-- 套餐图片 -->
          <view class="itemImage">
            <image
              class="_image"
              :src="item.shopImg || ``"
              mode="scaleToFill"
            />
          </view>
          <!-- 右侧套餐说明 -->
          <view class="rightExplain">
            <view class="nameWrapper">
              <view class="name">
                {{ item.name }}
              </view>
            </view>
            <view class="chartlet">
              <view
                class="tag"
                :class="
                  item.tagName === '限时' ? 'timeLimit' : item.tagName === '热销' ? 'Hot' : ''
                "
                >{{ item.tagName }}</view
              >
              <view class="limit" v-if="item.currentStock <= 3 && item.currentStock > 0"
                >仅剩{{ item.currentStock }}份</view
              >
            </view>
            <view class="price">
              <view
                class="originalPrice"
                :style="{
                  color: '#f14b4b',
                  fontSize: '32rpx',
                }"
              >
                <view class="symbol">￥</view>{{ Number(item.price).toFixed(2) }}</view
              >
              <view
                class="select"
                :class="item.currentStock <= 0 || !item.canBuy ? 'SoldOut' : ''"
                @click.stop="goToPay(item)"
                >{{ item.currentStock <= 0 ? '已售罄' : '立即抢购' }}</view
              >
            </view>
          </view>
        </view>
      </view>
      <view class="noData" v-else>
        <image class="_image" src="/static/images/noPack.png" mode="scaleToFill" />
        <view class="desc">当前没有在售券包哦~</view>
      </view>
    </scroll-view>
    <!-- 登录弹出层 -->
    <BjsPopup ref="popupRef" />
    <!-- 优惠券商品 -->
    <BjsCouponPackPopup
      ref="rulePopupRef"
      :rules="{
        rule: rulePopupObj.declare,
      }"
      :item="rulePopupObj"
      @goPay="goToPay(rulePopupObj)"
    />
    <BjsSkipPopup
      :img="skipPopupData.img"
      ref="SkipPopupRef"
      @receive="receive"
      @close="handleClose"
    />
  </view>
</template>

<style lang="scss" scoped>
.itemShow {
  flex: 1;
  min-height: 400rpx;
  flex: 1;
  margin-top: 24rpx;
  padding: 0 40rpx;
}
.rightGoods_scroll {
  height: 100vh;
  padding: 24rpx 24rpx 94rpx;
  width: 100%;
  overflow: hidden;
  background: #f5f5f5;
  ::-webkit-scrollbar {
    //隐藏scroll-view里面自带的滚动条
    display: none; //必加
    width: 0 !important;
    height: 0 !important;
    -webkit-appearance: auto !important;
    background: transparent;
    overflow: auto !important;
  }

  .itemBox {
    display: flex;
    flex-direction: column;
    width: 100%;
    .text {
      margin: 32rpx 0 24rpx 0;
      height: 36rpx;
      font-size: 26rpx;
      color: #000000e5;
    }
  }
}
// 循环套餐 item
.item {
  display: flex;
  width: 100%;
  height: 216rpx;
  margin-bottom: 20rpx;
  padding: 20rpx 40rpx 20rpx 20rpx;
  background: #fff;
  border-radius: 16rpx;
  &:last-child {
    margin-bottom: 48rpx;
  }
  .itemImage {
    display: flex;
    justify-content: center;
    // background-image: url('/static/images/eat_food_bg.png');
    background-size: cover; /* 设置背景图大小适应容器 */
    background-position: center; /* 设置背景图位置居中 */
    margin-right: 16rpx;
    width: 176rpx;
    height: 176rpx;
    border-radius: 8rpx;
    ._image {
      margin-top: 60rpx;
      width: 144rpx;
      height: 96rpx;
      border-radius: 8rpx;
    }
  }
}
.stocksIF {
  opacity: 0.7;
}
// 右侧套餐说明
.rightExplain {
  width: calc(100% - 192rpx); // 父级盒子自定义宽度
  .nameWrapper {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .name {
      height: 40rpx;
      line-height: 40rpx;
      font-size: 34rpx;
      color: #000000e5;
      // width: 100%; // 必定设置宽度
      white-space: nowrap; /* 防止换行 */
      overflow: hidden; /* 限制溢出内容隐藏 */
      text-overflow: ellipsis; /* 使用省略号 */
    }
    .imageWrapper {
      flex-shrink: 0;
      flex-grow: 1;
      min-width: 72rpx;
      margin-left: 4rpx;
      display: flex;
      .image {
        width: 24rpx;
        height: 24rpx;
      }
    }
  }
  .heat {
    width: 100%; // 必定设置宽度
    white-space: nowrap; /* 防止换行 */
    overflow: hidden; /* 限制溢出内容隐藏 */
    text-overflow: ellipsis; /* 使用省略号 */
    margin: 8rpx 0;
    height: 38rpx;
    font-size: 22rpx;
    color: #00000080;
  }
  .chartlet {
    display: flex;
    align-items: center;
    height: 36rpx;
    font-size: 24rpx;
    margin: 20rpx 0;
    .tag {
      margin-right: 8rpx;
      padding: 0 8rpx;
      height: 36rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 6rpx;
      color: $uni-color-motif;
      background-color: #f1ffee;
    }
    .timeLimit {
      color: #e14949;
      background-color: #fff6f6;
    }
    .Hot {
      color: #ff9c09;
      background-color: #fff5e5;
    }
    .limit {
      width: 104rpx;
      height: 36rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #8d6b25;
      border-radius: 6rpx;
      border: 1px solid #8d6b25;
    }
  }
  .price {
    position: relative;
    height: 40rpx;
    display: flex;
    flex-direction: column;
    align-items: baseline;
    .discountPrice {
      font-family: 'Rowdies';
      font-size: 32rpx;
      color: #f14b4b;
      margin-right: 8rpx;
      font-weight: 400;
      display: flex;
      align-items: center;
      .symbol {
        font-size: 18rpx;
      }
      .estimated_arrival {
        margin-left: 10rpx;
        font-size: 20rpx;
      }
    }
    .originalPrice {
      display: flex;
      align-items: center;
      font-family: 'Rowdies';
      font-weight: 400;
      font-size: 32rpx;
      color: #0000004d;
      .symbol {
        font-size: 18rpx;
      }
    }
    .select {
      position: absolute;
      bottom: 50%;
      transform: translate3d(0, -50%, 0);
      right: 0;
      width: 152rpx;
      height: 54rpx;
      line-height: 54rpx;
      text-align: center;
      font-size: 24rpx;
      color: #fff;
      background-color: $uni-color-motif;
      border-radius: 40rpx;
    }
    .SoldOut {
      background: #b3b2b2;
    }
  }
}
.noData {
  color: rgba(0, 0, 0, 0.5);
  text-align: center;
  font-family: 'PingFang SC';
  font-size: 28rpx;
  font-style: normal;
  font-weight: 400;
  line-height: normal;
  image {
    width: 376rpx;
    height: 246rpx;
    margin: 416rpx auto 48rpx;
  }
}
</style>
